package com.wish233.loadbalance.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.wish233.loadbalance.LoadBalancer;
import com.wish233.model.register.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询负载均衡器
 * @author WHH
 */
public class RoundRobinLoadBalancer implements LoadBalancer {

    private final AtomicInteger next = new AtomicInteger(0);


    @Override
    public ServiceMetaInfo select(List<ServiceMetaInfo> infoList, Map<String, Object> requestParams) {
        int size = infoList.size();
        if (CollectionUtil.isEmpty(infoList)) {
            return null;
        }
        //只有一个直接返回
        if (size == 1) {
            return infoList.get(0);
        }
        int idx = next.getAndIncrement() % size;
        return infoList.get(idx);
    }
}
